<template>
  <div>
   <Loading  class="animated" :class="{bounceInDown:showLoad,none:!showLoad}"/>
   <!-- 显示活动协议 -->
    <div v-transfer-dom>
      <popup v-model="showRuler" position="bottom">
        <ul class="ruler-contianer">
          <li class="title"><h1>用户服务协议</h1></li>
          <li><h3>定义及解释</h3></li>
          <li>1.1江西联通：中国联通江西省分公司。</li>
          <li>1.2平台：指由江西联通运营并管理的投票平台。</li>
          <li>1.3用户：指通过平台实名认证审查，参与2018年9月1日至9月30日平台投票活动的个人。</li>
          <li><h3>平台权利及义务</h3></li>
          <li>2.1平台及江西联通将对用户进行实名认证审核，并对用户信息的真实性进行必要的审查。</li>
          <li>2.2平台及江西联通会采取必要措施防范用户的欺诈行为。若用户存在欺诈行为或其他损害用户利益的行为，一经发现，平台将及时对欺诈行为进行公告，并根据情况取消该用户资格；</li>
          <li>2.3平台将收集本次活动中用户上传的视频和图片只用以江西联通微信公众号、微信朋友圈、腾讯视频宣传。</li>
          <li>2.4平台及江西联通会保守用户的个人隐私信息，非因法定原因不得泄露前述信息。</li>
          <li><h3>用户行为规范</h3></li>
          <li>3.1用户具有一切必要的权利及能力订立及履行本协议项下的所有义务和责任；本协议一经生效即对用户具有法律约束力。</li>
          <li>3.2用户承诺并保证其提供或发布的所有信息（包括但不限于用户的姓名、电话、身份证号码、参赛视频及照片等）是真实、原创、符合中国各项法律、法规及规范性文件以及活动的相关规则，不存在虚假、误导性陈述或重大遗漏。</li>
          <li>3.3用户承诺并保证其提供或发布的信息不存在以下情形：</li>
          <li>3.3.1违反中国各项法律、法规及规范性文件规定的；</li>
          <li>3.3.2危害国家安全、泄露国家秘密、颠覆国家政权、破坏国家统一的，煽动民族仇恨、民族歧视，破坏民族团结的，破坏国家宗教政策、宣扬邪教和封建迷信的，有损国家荣誉和利益的；</li>
          <li>3.3.3散布谣言、含有淫秽、色情、赌博、暴力、凶杀、恐怖或者教唆犯罪信息，扰乱社会秩序，破坏社会稳定的；</li>
          <li> 3.3.4侮辱或者诽谤他人，侵犯其他任何第三方知识产权及其他合法权益的；</li>
          <li>3.3.5发布、传送、传播、储存侵害他人名誉权、肖像权、知识产权、商业秘密等合法权利的内容；</li>
          <li>3.3.6其他含有法律、法规及规范性文件禁止内容的。</li>
          <li>3.4用户通过平台发布的涉嫌违法或涉嫌侵犯他人合法权利或违反本协议的信息，平台有权依据其独立判断对该等信息予以修改、编辑或删除，而无需事先通知相关用户。用户违反上述行为规范对任意第三方造成损害的，用户应独立承担由此造成的一切损失和法律责任，并应确保平台及平台免于承担因此产生任何损失或费用。</li>
          <li>3.5用户不得将获奖排名转售、赠与、转让给任何第三方。</li>
          <li>3.6用户承诺并保证若其违反上述承诺和保证而给平台或江西联通造成损失，用户同意对平台或江西联通因此而遭受的损失承担赔偿责任。</li>
          <li><h3>知识产权</h3></li>
          <li>4.1用户承诺通过其对平台发布、上传的所有内容拥有合法权利，不侵犯任何第三方的肖像权、隐私权、专利权、商标权、著作权等合法权利。</li>
          <li>4.2用户通过平台发布、上传的任何内容，用户授予平台及江西联通公司非独家的、可转授权的、不可撤销的、永久的、免费的许可使用权利，并可对上述内容进行修改、改写、改编、发行、翻译、创造衍生性内容及/或可以将前述部分或全部内容加以传播、表演、展示，及/或可以将前述部分或全部内容放入任何现在已知和未来开发出的以任何形式、媒体或科技承载的作品当中。若发生了任何一方无法预见、无法控制和无法避免的事件导致任何一方或双方不能履行其约定义务，该义务在不可抗力事件存在时中止，而义务的履行期应自动按中止期顺延而不加以处罚。</li>
          <li>4.3遭遇不可抗力的一方或双方应在发生不可抗力事件后的十天内向对方提供发生不可抗力和其持续期的适当证明，并尽最大努力减少因不可抗力事件带来的影响或损失。</li>
          <li>4.4因下列状况导致平台无法正常运作，平台及江西联通不承担损害赔偿责任，该等状况包括但不限于：</li>
          <li>4.4.1平台的系统停机维护期间；</li>
          <li>4.4.2平台所依赖的通讯设备出现故障；</li>
          <li>4.4.3因台风、地震、海啸、洪水、停电、战争、恐怖袭击等不可抗力之因素，造成平台系统障碍的；</li>
          <li>4.4.4由于黑客攻击、部门技术调整或故障、网站升级、其他第三方的问题等原因而造成的服务中断、延迟或者无法提供；</li>
          <li>4.4.5因政府部门要求、法律法规等不时颁布的监管性文件规定而造成的系统更新、维护、服务中断、延迟或者无法提供。</li>
        </ul>
        <div style="padding: 15px;">
          <x-button @click.native="showRuler = false" plain type="primary">同意协议</x-button>
        </div>
      </popup>
    </div>
    <!-- 处理图片-->
    <div v-transfer-dom>
      <x-dialog :show.sync="showDailog" class="dialog-demo">
        <div class="img-box">
          <img id="image"  :src="beforeSoloveImgUrl" style="max-width:100%">
        </div>
        <div>
          <x-icon type="ios-close" size="38"  @click.passive="clearInputImg"></x-icon>
          <!-- <x-icon type="ios-arrow-thin-right" size="38"  @click.passive="rotate"></x-icon> -->
          <span class="rotate" @click.passive="rotate"></span>
          <x-icon type="ios-checkmark" class="icon-red" size="38"  @click.passive="getImg('#image')"></x-icon>
        </div>
      </x-dialog>
    </div>
    <alert v-model="alert.show" :title="alert.title" :content="alert.msg"></alert>
    <div class="contianer">
      <x-input title="昵称:" v-model="user.nickname" required :max='8' class="unickname"  placeholder="八个字内(*必填)" ></x-input>
      <selector title="地市:" :options="options"  placeholder="(*必填)"  required @on-change="chanegVal" v-model="user.cityId" ></selector>
        <!-- <popup-radio title="地市:" :options="options" placeholder="(*必填)" @on-hide="chanegVal" v-model="user.cityId" ></popup-radio> -->
      <selector title="学校:" :options="schoolOptions"  placeholder="(*必填)"  required  v-model="user.universityId" ></selector>
        <!-- <popup-radio title="学校:" :options="schoolOptions" placeholder="(*必填)"  v-model="user.universityId" ></popup-radio> -->
      <x-input title="院系:" placeholder="选择学校院系(*必填)" required :max='8' v-model="user.department"></x-input>
      <x-textarea title="参赛宣言:" placeholder="请填写参赛宣言不超过15字(*必填)"  v-model="user.declaration"  :show-counter="true" :rows="2" :max="15" :autosize="true"></x-textarea>
        <p class="info"><span>温馨提示</span>* 提交并审核成功后，将无法修改</p>
      <p class="info"><span>实名认证</span>* 认证信息不会公布，只作为活动领奖唯一凭证</p>
      <x-input title="真实姓名:" v-model="user.realName" required :value="user.realName" placeholder="(*必填)"></x-input>
      <x-input title="手机号码:" v-model="user.phone" required :is-type="checkMb" :value="user.phone"  placeholder="(*必填)"></x-input>
      <x-input title="身份证号:" v-model="user.cardNo" required :is-type="checkIdentify" :value="user.cardNo" placeholder="(*必填)"></x-input>
       <p class="photo">参赛照片<span>*（可上传1~4张照片，照片过大可能影响像素）</span></p>
      <!-- 上传图片 -->
      <cell-box>
        <ul class="container-img-box">
          <li v-for="(items,key) of imgListUrl" :key="key"><img :src="items" alt="">
            <span class="cancel-btn" @click.passive="cancelImg(key)" >
              <icon type="cancel"></icon>
            </span>
            <span class="font-img"  v-if="key==0"></span>
          </li>
          <li >
          <label id="img" for="upimg" class="upimg animated"  :class="{none:!showUpImg}">
          </label>
            <input type="file" id="upimg" accept="image/*" hidden @change="handleImgChange" ref="inputer">
        <!-- <button @click.passive="upLoadImg(upimgList)">上传图片</button> -->
          </li>
        </ul>
      </cell-box>
      <!-- 上传视频-->
      <cell-box>
        <label id="video" for="upVideo" class="animated upVideo" >
        </label>
        <input type="file" id="upVideo" accept="video/*" @change="handleVideoChange" hidden ref="inputvideo">
        <!-- <button @click.passive="upLoadVideo()">上传视频</button> -->
      </cell-box>
      <x-progress :percent="videoPercent" :show-cancel="false" class="animated" ></x-progress>
        <p class="videoinfo animated" :class="{suc:showUpVideo,err:!showUpVideo}" ><span >{{videoinfo}}</span></p>
       <p><check-icon :value.sync="checkRuler" >我已阅读<a class="rulerbtn" @click.passive="ruler()">用户须知协议</a> </check-icon></p>
       <cell-box>
         <p class="sub-btn" v-if="!ifAuditing" @click.passive="sendUserInfo()"></p>
         <p class="sub-btn" v-if="ifAuditing" @click.passive="auditingUserInfo()"></p>
      </cell-box>
      <cell-box class="none">
       <video id="myvideo" :src="videoUrl"></video>
      </cell-box>
    </div>
</div>
</template>
<script>
import Loading from '@/components/com/Loading';
import Myvideo from '@/components/com/Myvideo';
import { idCardNoUtil, getAge } from '@/assets/lib/identifyCk.js'
import { CellBox, Alert, GroupTitle, Popup, PopupRadio, XProgress, Group, XButton, XInput, Selector, XTextarea, PopupPicker, Icon, XDialog, CheckIcon, TransferDomDirective as TransferDom } from 'vux'
import Qs from 'qs'
import {  getServerHost,
  preventMove,
  GetRequest,
  checkMobile,
  checkQq} from '@/assets/lib/tool.js'

import { setTimeout } from 'timers';
import { log } from 'util';
const BIGSIZE = (1024 * 1024);
export default {
  directives: {
    TransferDom
  },
  components: {
    Myvideo,
    Loading,
    Group,
    GroupTitle,
    XInput,
    Selector,
    PopupPicker,
    XTextarea,
    CellBox,
    XButton,
    Icon,
    XDialog,
    CheckIcon,
    Alert,
    XProgress,
    Popup,
    PopupRadio
  },
  data() {
    return {
      options: [],
      school: [],
      checkRuler: false,
      showRuler: false,
      fileName: '',
      schoolOptions: ['请先选择学校'],
      schoolRead: true,
      videoPercent: 0,
      imgLoad: '',
      alert: {
        show: false,
        title: '',
        msg: ''
      },
      rebackvideoUrl: '',//显示视频的视频源
      showVideo: false,
      user: {
        openid: GetRequest().openid,
        nickname: '',
        cityId: '',
        universityId: '',
        department: '',
        declaration: '',
        realName: '',
        phone: '',
        cardNo: '',
        image1Path: '',
        image2Path: '',
        image3Path: '',
        image4Path: '',
        videoPath: ''
      },
      ifAuditing: false,
      showLoad: false,
      videoinfo: '',
      imgListUrl: [],
      upimgList: [],
      videoUrl: '',
      beforeSoloveImgUrl: '',//处理之前的图片链接 默认一张图片
      showDailog: false, //处理弹窗
      numberValue: 0,
      showUpImg: true,
      showUpVideo: true,
      openid: GetRequest().openid,
      pathUrl: 'http://118.212.184.170/wxjx/file',
      upImgUrl: 'http://118.212.184.170/wxjx/goddess/upload/uploadImage',
      upVideoUrl: 'http://118.212.184.170/wxjx/goddess/upload/uploadVedio',
      queryList: '/wxjx/goddess/common/university/queryList',
      submitUserUrl: '/wxjx/goddess/common/user/submit',
      updateUrl: '/wxjx/goddess/common/user/update',
      queryInfoMyselfUrl: '/wxjx/goddess/common/user/queryInfoMyself',
    }
  },
  watch: {
    user(val) {
      return val;
    }
  },
  mounted() {
    this.$nextTick(() => {
      //获取学校列表
      this.getSchoolList();
      //初始化裁剪图片
      this.initImg();
    })
  },
  watch: {
    beforeSoloveImgUrl(newold, val) {
      // console.log(val);
      return newold;
    },
    schoolOptions(val) {
      // console.log(val);
      return val;
    },
    videoinfo(val) {
      return val;
    }
  },
  computed: {

  },
  methods: {
    //规则
    ruler() {
      this.showRuler = true;
    },
    getStatus(e) {
      this.showVideo = false;
    },
    //修改用户信息
    auditingUserInfo() {
      var vm = this;
      var list = [];
      vm.judgeInfo().then(rs => {
        console.log(rs);
        if ('999' == rs) {
          return;
        } else if ('200' == rs) {
          vm.showLoad = true;
          //上传图片和添加的视频给后台
          Promise.all([...vm.upLoadImg(vm.upimgList), vm.upLoadVideo()]).then((result) => {
            console.log('rs', result);
            //将返回的视频和图片资源放到提交对象中
            result.map(items => {
              if (undefined == items) {
                return;
              }
              list.push(items.value);
              if ('img' == items.key) {
                [vm.user.image1Path, vm.user.image2Path, vm.user.image3Path, vm.user.image4Path] = [...list]
                console.log(vm.user);
              } else if ('video' == items.key) {
                vm.user.videoPath = items.value;
              }
            })
            //提交数据给后台,内部函数
            auditingForm();
          }).catch(result => {
            vm.showLoad = false;
            vm.alert.show = true;
            vm.alert.title = '提示';
            vm.alert.msg = result;
            console.log(result);
          })
        }
      })
      //修改用户信息
      function auditingForm() {
        var config = {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          }
        }
        vm.$http.post(getServerHost() + vm.updateUrl, Qs.stringify(vm.user), config).then(result => {
          console.log(result);
          result = result.data;
          if ('200' == result.code) {
            vm.showLoad = false;
            vm.alert.show = true;
            vm.alert.title = '提示';
            vm.alert.msg = '上传成功！';
            vm.$router.push({ name: 'auditing', query: { openid: vm.openid } });
          } else {
            vm.alert.show = true;
            vm.alert.title = '提示';
            vm.alert.msg = result.msg;
          }
        })
      }
    },
    //提交用户信息
    sendUserInfo() {
      var vm = this;
      var list = [];
      vm.judgeInfo().then(rs => {
        console.log(rs);
        if ('999' == rs) {
          return;
        } else if ('200' == rs) {
          vm.showLoad = true;
          //上传图片和添加的视频给后台
          Promise.all([...vm.upLoadImg(vm.upimgList), vm.upLoadVideo()]).then((result) => {
            console.log('rs', result);

            //将返回的视频和图片资源放到提交对象中
            result.map(items => {
              if (undefined == items) {
                return;
              }
              list.push(items.value);
              if ('img' == items.key) {
                [vm.user.image1Path, vm.user.image2Path, vm.user.image3Path, vm.user.image4Path] = [...list]
                console.log(vm.user);
              } else if ('video' == items.key) {
                vm.user.videoPath = items.value;
              }
            })
            //提交数据给后台,内部函数
            sendForm();
          }).catch(result => {
            vm.showLoad = false;
            vm.alert.show = true;
            vm.alert.title = '提示';
            vm.alert.msg = result;
            console.log(result);
          })
        }
      })

      //提交ajax
      function sendForm() {
        var config = {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          }
        }
        vm.$http.post(getServerHost() + vm.updateUrl, Qs.stringify(vm.user), config).then(result => {
          console.log(result);
          result = result.data;
          if ('200' == result.code) {
            vm.showLoad = false;
            vm.alert.show = true;
            vm.alert.title = '提示';
            vm.alert.msg = '上传成功！';
            vm.$router.push({ name: 'auditing', query: { openid: vm.openid } });
          } else {
            vm.alert.show = true;
            vm.alert.title = '提示';
            vm.alert.msg = result.msg;
          }
        })
      }
    },
    //判断信息是否正确
    judgeInfo() {
      var vm = this;
      return new Promise((resolve, reject) => {
        if (!Boolean(vm.user.openid) || !Boolean(vm.user.nickname) || !Boolean(vm.user.cityId) || !Boolean(vm.user.universityId) || !Boolean(vm.user.declaration) || !Boolean(vm.user.realName) || !checkMobile(vm.user.phone) || !idCardNoUtil.checkIdCardNo(vm.user.cardNo)) {
          console.log(vm.user);
          vm.alert.show = true;
          vm.alert.title = '提示';
          vm.alert.msg = '请根据提示补全用户信息';
          resolve('999')
        } else {
          console.log(vm.user);
          if (!vm.checkRuler) {
            vm.alert.show = true;
            vm.alert.title = '提示';
            vm.alert.msg = '请同意用户协议';
            resolve('999')
          } else {
            resolve('200')
          }
        }
      })
    },
    // 验证手机号
    checkMb() {
      var vm = this;
      if (checkMobile(vm.user.phone)) {
        return { valid: true };
      } else {
        return { valid: false, msg: '请输入正确的手机号' };
      }
    },
    //验证身份证号码
    checkIdentify() {
      var vm = this;
      console.log(idCardNoUtil.checkIdCardNo(vm.user.cardNo));
      if (idCardNoUtil.checkIdCardNo(vm.user.cardNo)) {
        return { valid: true };
      } else {
        return { valid: false, msg: '请输入正确的身份证号' };
      }
    },
    //获取学校的信息
    getSchoolList() {
      var vm = this;
      this.$http(getServerHost() + this.queryList).then(rs => {
        rs = rs.data;
        vm.options = rs.res.cityList;
        vm.school = rs.res.universityList;
      })
    },
    // 显示学校
    chanegVal(value) {
      console.log(value);
      this.value2 = value;
      this.schoolRead = false;
      let schoolmap = [];
      this.school.map(items => {
        if (items.cityId == value) {
          schoolmap.push({ key: items.key, value: items.value })
        }
      })
      this.schoolOptions = schoolmap;
    },
    //删除图片数组和清空input框
    cancelImg(index) {
      this.$refs.inputer.value = '';
      this.imgListUrl.splice(index, 1)
      if (!Boolean(this.imgListUrl.length)) {
        this.showUpImg = true;
      }
      this.upimgList.splice(index, 1);
      console.log(this.imgListUrl, this.upimgList);
    },
    //上传图片
    upLoadImg(imglist) {
      console.log('upimg');
      console.log(imglist);
      let vm = this;
      if (!Boolean(imglist.length)) {
        vm.alert.show = true;
        vm.alert.title = '提示';
        vm.alert.msg = '请添加图片';
        return;
      }
      let imgUrl = [];
      if (vm.user.image1Path) {
        //提交数据给后台,内部函数
        return [];
      }
      //上传generator函数
      function* loopUploadimg(imglist) {
        for (let blob of imglist) {
          //上传图片
          yield (function () {
            return new Promise((resolve, reject) => {
              var config = {
                headers: {
                  'Content-Type': 'multipart/form-data'
                }
              }
              var formdata = new FormData()
              formdata.append('file', blob)
              formdata.append('openid', vm.openid)
              formdata.append('filename', 'blob.png');
              vm.$http.post(vm.upImgUrl, formdata, config).then(res => {
                if ('200' == res.data.code) {
                  resolve({ key: 'img', value: res.data.res })
                } else {
                  reject(res.data.msg)
                }
              })
            })
          })();
        }
        return imgUrl;
      }
      //返回promsie用于整个上传promise的子promise 
      //多个promise对象上传返回
      // Promise.all([...loopUploadimg(imglist)]).then(result => {
      //   //全局数组接受返回的图片地址的值
      //   [vm.user.image1Path, vm.user.image2Path, vm.user.image3Path, vm.user.image4Path] = [...result]
      //   console.log(vm.user);
      //   return resolve(result);
      // })
      return [...loopUploadimg(imglist)]
    },

    //添加视频
    handleVideoChange() {
      console.log('ok');

      var vm = this;
      let inputDOM = this.$refs.inputvideo;
      let file = inputDOM.files[0];
      let size = file.size / BIGSIZE;
      console.log(size);
      vm.videoinfo = ``
      this.videoUrl = URL.createObjectURL(file)
      this.fileText = '';
      if (size > 15) {
        vm.alert.show = true;
        vm.alert.title = '提示';
        vm.alert.msg = '文件过大';
        return;
      }
      //TODO:控制时长的问题
      vm.videoinfo = `添加成功,等待提交!`;
      vm.fileName = file.name;
      vm.onChange && vm.onChange(file, inputDOM.value);
      return;
      new Promise((resolve, reject) => {
        //判断时长
        var myvideo = document.getElementById('myvideo')
        myvideo.addEventListener("loadedmetadata", function () {
          var tol = this.duration;//获取总时长
          if (tol > 10) {
            vm.alert.show = true;
            vm.alert.title = '提示';
            vm.alert.msg = '文件时长过长(最长15s),请重新添加';
            vm.videoinfo = `文件时长过长(最长15s),请重新添加`;
            resolve(false);
          } else {
            vm.videoinfo = `添加成功,等待提交!`
            resolve(true);
          }
        });
      }).then(result => {
        if (result) {
          vm.showUpVideo = true;
          vm.fileName = file.name;
          vm.onChange && vm.onChange(file, inputDOM.value);
        } else {
          vm.showUpVideo = false;
        }
      })
    },
    //上传视频
    upLoadVideo() {
      let vm = this;
      if (!Boolean(this.$refs.inputvideo.files[0])) {
        vm.alert.show = true;
        vm.alert.title = '提示';
        vm.alert.msg = '请添加视频';
        return;
      }
      var formdata = new FormData();
      let videoUrl = URL.createObjectURL(this.$refs.inputvideo.files[0]);
      formdata.append('file', this.$refs.inputvideo.files[0])
      // formdata.append('fileName', this.fileName)
      formdata.append('openid', vm.openid)
      return new Promise((resolve, reject) => {
        var config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: progressEvent => {
            var complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
            vm.videoPercent = complete;
          }
        }

        this.$http.post(this.upVideoUrl, formdata, config).then(res => {
          console.log(res.data);
          if ('200' == res.data.code) {
            vm.showUpVideo = true;
            resolve({ key: 'video', value: res.data.res })
          } else {
            vm.showUpVideo = false;
            vm.videoinfo = res.data.msg;
            reject(res.data.msg)
          }
        })
      })
    },
    //初始化图片
    initImg() {
      var vm = this;
      var _this = $('#image');
      setTimeout(() => {
        _this.cropper({
          aspectRatio: 640 / 640,//图片的宽高比
          scalable: false,//是否允许缩放图像。
          zoomOnTouch: false,//是否可以通过拖动触摸来放大图像。
          zoomable: false,//是否允许放大图像。
          cropBoxResizable: false,//是否通过拖动来调整剪裁框的大小。
          modal: true,//黑色模态框
          dragMode: 'none',//‘crop’: 可以产生一个新的裁剪框3 
          // ‘move’: 只可以移动3
          // ‘none’: 什么也不处理
          responsive: false,
          restore: false,
          autoCropArea: 1,
          checkOrientation: true,//-检查当前图像的Exif定向信息
          toggleDragModeOnDblclick: false,//点击两次时可以在“crop”和“move”之间切换拖拽模式
          viewMode: 1,//视图模式
          // 0：没有限制，3可以移动到2外。
          // 1: 3只能在2内移动。
          // 2：2图片 不全部铺满1 （即缩小时可以有一边出现空隙）
          // 3：2图片填充整个1
          preview: ".small",//预览容器
          crop: function (e) {
            // console.log(e);
          },
          ready: function () {
            // vm.orientImg();
            // vm.showDailog = true;
          },
          cropmove: function () {
          }
        });
      }, 500)

    },
    //旋转
    rotate() {
      $('#image').cropper('rotate', 90);
    },
    //删除添加的图片文件
    clearInputImg() {
      this.$refs.inputer.value = '';
      this.showDailog = false;
    },
    //获取裁剪后的图片
    getImg(el) {
      let vm = this;
      vm.showLoad = true;
      //**dataURL to blob**
      function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      }
      vm.showDailog = false;
      new Promise((resolve, reject) => {
        var canvas = $(el).cropper('getCroppedCanvas');//获取当前截取的图片的大小
        var base64Url_mini = canvas.toDataURL('image/png')

        resolve(dataURLtoBlob(base64Url_mini));
        // $('.cavans>img').attr('src', base64Url)  //在body显示出canvas元素
        // $('.cavans2>img').attr('src', base64Url_mini) //在body显示出canvas元素
      }).then(file => {
        console.log('newfile', file);
        if (file.size > 1024 * 2) {
          // 这里可以加个文件大小控制
          // let minisize = 2048 / this.file.size;
          let minisize = 1;
          this.canvasMinify(file.size, file, this.fileName, minisize).then(result => {
            vm.imgListUrl.push(URL.createObjectURL(result.blob));
            vm.upimgList.push(result.blob);
            if (vm.imgListUrl.length == 4) {
              vm.showUpImg = false;
            } else {
              vm.showUpImg = true;
            }
            vm.fileText = '';
            vm.showLoad = false;
            //将图片base64传给父容器
          });
        }

      })
    },
    //添加图片
    handleImgChange() {
      var vm = this;
      let inputDOM = this.$refs.inputer
      vm.file = inputDOM.files[0];
      vm.fileName = vm.file.name;
      if (inputDOM.files[0]) {
        vm.showLoad = true;
      }
      // console.log('imgurl', this.imgListUrl);
      //判断图片的大小
      // console.log('filesize', this.file.size);

      let size = this.file.size / 1024;
      // if (size > 1024 * 2) {
      //   // 这里可以加个文件大小控制
      //   let minisize = 1024 / this.file.size;
      //   this.canvasMinify(size, vm.file, this.fileName, minisize).then(result => {
      //     console.log('result', result);
      //     if (!Boolean(result.blob)) {
      //       vm.alert.show = true;
      //       vm.alert.title = '提示';
      //       vm.alert.msg = '图片存在问题,请重新添加';
      //       // vm.videoinfo = `图片存在问题,请重新添加`;
      //     } else {
      //       vm.showDailog = true;
      //       vm.showLoad = false;
      //     }
      //     vm.beforeSoloveImgUrl = window.URL.createObjectURL(result.blob);;
      //     $('#image').cropper('replace', vm.beforeSoloveImgUrl, false);
      //     vm.onChange && vm.onChange(result.blob, inputDOM.value);
      //   });
      //   return;
      // }
      vm.beforeSoloveImgUrl = window.URL.createObjectURL(vm.file);
      if (vm.beforeSoloveImgUrl) {
        vm.showDailog = true;
        vm.showLoad = false;
      }
      //console.log('before', vm.file);
      $('#image').cropper('replace', vm.beforeSoloveImgUrl, false);
      vm.onChange && vm.onChange(vm.file, inputDOM.value);
    },
    //canvas压缩图片
    canvasMinify(size, file, name, minisize) {
      let vm = this;
      // console.log(file);
      return new Promise((resolve, reject) => {
        var reader = new FileReader();
        let base64img = '';
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          var imgObj = new Image();
          imgObj.src = this.result;
          imgObj.onload = function (a) {
            var canvas = document.createElement('canvas');
            canvas.width = imgObj.width;
            canvas.height = imgObj.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(imgObj, 0, 0, canvas.width, canvas.height);
            base64img = canvas.toDataURL("image/jpeg", minisize);
            if (!Boolean(base64img)) {
              reject(false);
            }
            // console.log(base64img); 
            resolve({
              blob: vm.convertBase64UrlToBlob(base64img, name),
              base64: base64img
            })
          }
        }
      })
    },
    //base64转blob
    convertBase64UrlToBlob(urlData, name) {
      var bytes = window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte  
      //处理异常,将ascii码小于0的转换为大于0  
      var ab = new ArrayBuffer(bytes.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      console.log(new Blob([ab], { type: 'image/png' }));
      return new Blob([ab], { type: 'image/png' });
    }
  }
}
</script>
<style lang="less" scoped >
@import "../../assets/style/common.min.css";
.none {
  display: none;
}
.rotate {
  display: inline-block;
  position: relative;
  margin: 0 50px;
  width: 64px;
  height: 64px;
  line-height: 64px;
  background: url("../../assets/img/rotate.png") no-repeat;
  background-size: 64px 64px;
}
::-webkit-input-placeholder {
  color: red !important;
}
.preview-c {
  position: fixed;
  top: 0;
  width: 100%;
  .small {
    margin: 0 auto;
    overflow: hidden;
    width: 480px;
    height: 270px;
  }
}
.ruler-contianer {
  padding: 30px;
  .title {
    text-align: center;
    h1 {
      margin: 20px 0;
    }
  }
  li {
    padding: 5px 0;
    line-height: 1.5em;
  }
}
.popcontainer {
  overflow: hidden;
  width: 100%;
  height: 100%;
}
.canvas {
  width: 100%;
}
.btn-group {
  position: fixed;
  bottom: 20px;
  width: 100%;
  span {
    width: 25%;
    padding: 10px;
  }
  span:first-child {
    width: 50px;
    background: #e4393c;
    z-index: 999;
  }
  span:nth-child(2) {
    width: 50px;
    background: green;
    z-index: 999;
  }
  span:nth-child(3) {
    width: 50px;
    background: blue;
    z-index: 999;
  }
}
video {
  width: 640px;
  height: auto;
}
.info {
  padding: 10px 15px;
  text-align: left;
  font-size: 18px;
  margin-left: 15px;
  span {
    font-size: 24px;
    color: #ff5a65;
    font-weight: bold;
  }
}
.suc {
  color: #017c0a;
}
.err {
  color: #c10909;
}
.videoinfo {
  text-align: left;
  font-weight: bold;
}
.rulerbtn {
  color: #f6244f;
  text-decoration: underline;
}
.myvideo {
  margin: 0 auto;
  width: 246px;
  min-height: 161px;
  background: url("../../assets/img/video.png") no-repeat;
  background-size: 246px 161px;
}
.sub-btn {
  margin: 0 auto;
  width: 244px;
  height: 68px;
  background: url("../../assets/img/submit.png") no-repeat;
  background-size: 100% 100%;
}
.upimg {
  display: inline-block;
  width: 117px;
  height: 115px;
  background: url("../../assets/img/upimg.png") no-repeat;
  background-size: 100% 100%;
}
.font-img {
  display: inline-block;
  width: 103px;
  height: 31px;
  background: url("../../assets/img/font-img.png") no-repeat;
  background-size: 100% 100%;
}
.upVideo {
  display: inline-block;
  width: 515px;
  height: 109px;
  background: url("../../assets/img/upvideo.png") no-repeat;
  background-size: 100% 100%;
}
.cancel-img {
  align-self: center;
  margin: 0 auto;
  width: 245px;
  height: 76px;
  background: url("../../assets/img/auditing-btns.png") no-repeat 0 -82px;
  background-size: 528px 168px;
}
.photo {
  padding: 10px 15px;
  text-align: left;
  font-size: 24px;
  span {
    margin-left: 15px;
    color: #ff5a65;
    font-size: 18px;
    font-weight: bold;
  }
}
.contianer {
  width: 547px;
  margin: 0 auto;
  font-size: 24px;
}
.container-img-box {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  li {
    width: 50%;
    min-height: 50px;
    position: relative;
    display: flex;
    padding: 0 10px;
    flex-direction: column;
    justify-content: space-between;
    img {
      padding: 5px;
      border-radius: 10px;
      border: 2px solid #fff;
      width: 100%;
    }
    .font-img {
      align-items: center;
      margin: auto;
    }
    .cancel-btn {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 333;
    }
  }
}
</style>
